package com.chapter16.ThreadPoolExecutor;

import java.util.concurrent.*;

/**
 * @author 宋鑫宇
 * @version 1.0
 * 使用线程池执行实现了 Callable 接口的线程任务
 */
public class ThreadPoolExecutor01 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //新建线程池
        ThreadPoolExecutor pool = new ThreadPoolExecutor(3, 5, 3,
                TimeUnit.SECONDS, new ArrayBlockingQueue<>(3),
                Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());
        //把一个Callable任务交给线程池处理,返回一个Future对象，调用get方法
        Future<String> f1 = pool.submit(new B(100));
        Future<String> f2 = pool.submit(new B(200));
        Future<String> f3 = pool.submit(new B(300));
        Future<String> f4 = pool.submit(new B(400));
        System.out.println(f1.get());
        System.out.println(f2.get());
        System.out.println(f3.get());
        System.out.println(f4.get());

    }
}

class B implements Callable<String> {
    private int n;

    public B(int n) {
        this.n = n;
    }

    @Override
    public String call() throws Exception {
        int sum = 0;
        for (int i = 1; i <= n; i++) {
            sum += i;
        }
        return Thread.currentThread().getName() + " " + sum + " ";
    }
}
